import Vue from 'vue';
import Vuex from 'vuex';
import router from '@/router';

const UserInfoKey = "UserInfoKey";

Vue.use(Vuex);

let currentUserInfo = JSON.parse(localStorage.getItem(UserInfoKey)) || {};
const store = new Vuex.Store({
    state: {
        language: "zh-Hans",
        userInfo: currentUserInfo,
        token: currentUserInfo.token || ""
    },
    mutations: {
        SET_USER(state, ctx) {
            state.userInfo = {...state.userInfo, ...ctx};
            if (state.userInfo.token.length > 0) {
                state.token = state.userInfo.token;
            }else {
                state.userInfo.token = state.token;
            }
            localStorage.setItem(UserInfoKey, JSON.stringify(state.userInfo));
            console.log("用户信息改变2", state.userInfo);
        },
        LOGIN_OUT(state, ctx) {
            localStorage.removeItem(UserInfoKey);
            router.replace('login');
        }
    }
});

export default store;